import axios from 'axios';
import router from '../router/index';
import store from '../store'


axios.defaults.timeout = 9000000000;
axios.defaults.baseURL = process.env.API_ROOT       // 不同环境, 不同地址

axios.interceptors.request.use(
  config => {
    let token = localStorage.getItem('Authorization');
    if (token) {
      config.headers.Authorization = token;
    }
  
    return config;
    
  },
  err => {
    return Promise.reject(err);
  });

  console.log(router)

  axios.interceptors.response.use(
    response => {
      if (response) {
        switch (response.data.status) {
          case 400:
            localStorage.clear();
            router.replace({
              name: 'login',
              query: router.currentRoute.query
            });
          case 401:
            localStorage.clear();
            router.replace({
              name: 'login',
              query: router.currentRoute.query
            });
        }
      }
      return response;
    },
    error => {
      let err = String(error).includes('401');
      if (err) {
        localStorage.clear();
        router.replace({
          name: 'login',
          query: router.currentRoute.query
        });
        return Promise.reject('token过期,请重新登陆!');
      } else {
        return Promise.reject(error);
      }
    }
  );
  export default axios;